import re
import time
from flask import request
from flask_restful import abort
from flask_login import current_user, login_user
from funcy import project
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import IntegrityError
from funcy import partial

from redash import models, limiter
from redash.permissions import (
    require_permission,
    require_admin_or_owner,
    is_admin_or_owner,
    require_permission_or_owner,
    require_admin_default,
)
from redash.handlers.base import (
    BaseResource,
    require_fields,
    get_object_or_404,
    paginate,
    order_results as _order_results,
)

from redash.authentication.account import (
    invite_link_for_user,
    send_invite_email,
    send_password_reset_email,
    send_verify_email,
)
from redash.settings import parse_boolean
from redash import settings

class ContractFinishNewResource(BaseResource):
    def get(self):
        result = models.ContractFinish.get_id()
        return result[0]

    @require_admin_default
    def post(self):
        req = request.get_json(force=True)
        require_fields(req, ("code","name"))

        contractfinish = models.ContractFinish(
        id=req["id"],
        org=self.current_org,
        userid=req["userid"],
        bill_date = req["bill_date"],
        contractsid = req["contractsid"],
        code = req["code"],
        name = req["name"],
        status =req["status"],
        message =req["message"],
        sourcetype =req["sourcetype"],
        sourceid =req["sourceid"],
        )
        contractactivity = models.ContractActivity(
        userid=req["userid"],
        contractsid = req["contractsid"],
        message ="合同验收",
        sourcetype ="contractfinish",
        sourceid =req["id"],
        )

        try:
            models.db.session.add(contractfinish)
            models.db.session.add(contractactivity)
            models.db.session.commit()
        except IntegrityError as e:
            if "code" in str(e):
                abort(400, message="编号已存在.")
            abort(500)


class ContractFinishResource(BaseResource):
    def get(self, contractfinish_id):
        result = models.ContractFinish.get_by_id(contractfinish_id)
        return result.to_dict()

    @require_admin_default
    def post(self, contractfinish_id):
        req = request.get_json(force=True)
        require_fields(req, ("code","name"))

        contractfinish = models.ContractFinish.get_by_id(contractfinish_id)
        params = dict(bill_date=req["bill_date"], contractsid=req["contractsid"], code=req["code"],
                name=req["name"],sourceid=req["sourceid"],
                sourcetype=req["sourcetype"],message=req["message"])
        try:
            self.update_model(contractfinish, params)
            
            models.db.session.commit()
        except IntegrityError as e:
            if "code" in str(e):
                abort(400, message="编号已存在.")
            abort(500)

class ContractFinishdeleteResource(BaseResource):
    @require_admin_default
    def post(self, contractfinish_id):
        contractfinish =  models.ContractFinish.get_by_id(contractfinish_id)
        contractactivity = models.ContractActivity.get_by_sourceid("contractfinish",contractfinish_id)
        models.db.session.delete(contractfinish)
        models.db.session.delete(contractactivity)
        models.db.session.commit()

class ContractFinishListResource(BaseResource):
    def post(self):
        req = request.get_json(force=True)
        page = req["page"]
        page_size = req["pagesize"]
        code = req["code"]
        name = req["name"]
        contractcode = req["contractcode"]
        contractname = req["contractname"]
        type = req["type"]
        userid = str(req["userid"])
        orderfield = req["field"] if "field" in req else ""
        if orderfield=="code" :
            orderfield ="t1.code"
        elif orderfield=="contractcode":
            orderfield ="t2.code"
        elif orderfield=="contractname":
            orderfield ="t2.name"
        elif orderfield=="name":
            orderfield ="t1.name"
        elif orderfield=="partyaname":
            orderfield ="t3.strcustomername"
        elif orderfield=="typename":
            orderfield ="t4.typename"
        elif orderfield=="amount":
            orderfield ="t2.amount"
        else:
            orderfield ="t1.id"
        order = req["order"] if "order" in req else 0

        strwhere ="t1.org_id=" +str(self.current_org.id)
        if code !="" :
            strwhere = strwhere + " and t1.code like '%"+code+"%'"
        if name !='' :
            strwhere = strwhere + " and t1.name like '%"+name+"%'"
        if contractcode !='' :
            strwhere = strwhere + " and t2.code like '%"+contractcode+"%'"
        if contractname !='' :
            strwhere = strwhere + " and t2.name like '%"+contractname+"%'"
        if type !='' :
            strwhere = strwhere + " and  '"+type+"' = ANY(t2.type)"
        if userid !='':
            strwhere = strwhere + """ and  exists(select orgpower_ids from public.users where id='""" + userid + """' 
            and (t1.departmentid=any(orgpower_ids) or 0=any(orgpower_ids)))"""

        strgetfield =""" t1.*,t2.code as contractcode,t2.name  as contractname,
        t3.strcustomername as partyaname,t4.typename,
                    case when t1.status=2 then '已审核' when t1.status=1 then '审核中' else '草稿' end strstatus"""

        tblname = """public.contractfinish t1 inner join public.contracts t2 on t1.contractsid=t2.id
                left join public.customertemp t3 on t2.party_aid=t3.id  left join
                    public.contracttypeview t4 on t2.type =t4.type  and t2.org_id=t4.org_id"""
        #orderfield ="t1.id"
        result = models.ContractApply.get_pagequery(tblname,strgetfield,orderfield,page_size,page,order,strwhere)
        return result[0]
